package com.chixing;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Vector;

import static com.sun.tools.classfile.AccessFlags.Kind.Method;

public class Mypool {
    private int init_size = 3;
    private int max_size = 10;
    private int currect_count = 0;
    private int used_count = 0;
    private Vector<Connection> pool = new Vector<Connection>();

    public Mypool() {
        for (int i = 0; i < init_size; i++) {
            Connection conn = createConnection();
        }
        currect_count = init_size;
    }

    private synchronized Connection createConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            final Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/datt", "root", "1234");
            Connection proxy = (Connection) Proxy.newProxyInstance(conn.getClass().getClassLoader(),
                    conn.getClass().getInterfaces(),
                    new InvocationHandler() {
            public Object invoke (Object proxy, Method method, Object[]args) throws Throwable {
                Object result = null;
                String methodName = method.getName();
                if (methodName.equals("close") && currect_count < init_size) {
                    pool.add(conn);
                    currect_count++;
                    used_count--;
                } else if (methodName.equals("close") && currect_count >= init_size) {
                    conn.close();
                    currect_count--;
                } else {
                    result = method.invoke(conn, args);
                }
                return result;
            }

            return proxy;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public Connection getConnection() {
        if(currect_count >0){
            used_count++;
            currect_count--;
            System.out.println("");
            return pool.remove(0);
        }
        if(used_count < max_size){
            System.out.println("");
            used_count++;
            return createConnection();
        }
        throw new RuntimeException("");
    }
    public static void main (String[] args) {
        Mypool pool = new Mypool();
        for (int i = 0; i < 10; i++) {
            new ConnThread(myPool).start();
        }
    }
}
